import { IconButton } from "@fluentui/react";
import useMessage from "antd/es/message/useMessage";
import React, { useEffect, useRef, useState } from "react";
import Alymodel from "../../mysql_interface/model";
import { asyncInquireusertotpdataid9, asyncossupload8 } from "../api/api";
interface P {
    getuser: Alymodel.IMuser,
    cid: number
    num: number
    lessionid: number
}

const Sectionw: React.FunctionComponent<P> = (p) => {
    const [x, setx] = useState(true)
    const [messageApi, contextHolder] = useMessage();

    // 全屏相关
    const [isPdf, setIsPdf] = React.useState<boolean>();


    const aliyunPreview = useRef<HTMLIFrameElement>(null)
    useEffect(() => {
        window.addEventListener(
            "message",
            message,
            false
        );
        return () => {
            window.removeEventListener('message', message)
        }
    }, [x])
    function message(e: MessageEvent<any>) {
        let res;
        if (e.data && typeof e.data === "string") {
            res = JSON.parse(e.data);
            switch (res.action) {
                case "preview.ready":
                    init(p.cid);
                    break;
                case "logic.refreshToken":
                    setToken();
                    break;
                case "message.error":
                    break;
            }
        }
    }
    useEffect(() => {
        setx(true)
        Refresh()

    }, [p.cid, p.lessionid])

    async function setToken() {
        const data = await asyncossupload8();
        sendMessage("logic.setToken", {
            region: "oss-cn-beijing",
            accessKeyId: data.accessKeyId,
            accessKeySecret: data.accessKeySecret,
            stsToken: data.securityToken,
            bucket: "hterobot-pdf",
        });
    }
    async function init(cid: number) {
        if (!x) return;
        setx(false);
        const { userid } = p.getuser;
        const arr = await asyncInquireusertotpdataid9({
            course_ID: cid,
            // num: p.num,
            lessionid: p.lessionid
        });
        const url = arr.TgtUri;
        // 全屏相关
        const fileType = urlDemo(url, 2) || ''
        setIsPdf(fileType.includes('pdf'))

        if (arr) {
            const {
                accessKeyId,
                accessKeySecret,
                securityToken,
            } = await asyncossupload8();
            sendMessage("preview.init", {
                url,
                region: "oss-cn-beijing",
                bucket: "hterobot-pdf",
                accessKeyId,
                accessKeySecret,
                stsToken: securityToken,
                wmType: 1,
                wmValue: String(userid),
                wmColor: "rgba(192, 192, 192, 0.2)",
                copy: 1
            });
        } else {
            messageApi.error('没有权限哦！');
        }
    }

    function sendMessage(action: string, data: any) {
        if (aliyunPreview.current) {
            aliyunPreview.current.contentWindow?.postMessage(json2str({
                action: action,
                data: data,
            }),
                "*")

        }
    }

    function Refresh() {
        if (aliyunPreview.current && aliyunPreview.current.contentWindow) {
            aliyunPreview.current.contentWindow.location.href = `https://preview.imm.aliyun.com/index.html?_q=${Math.random()}`
        }
    }

    function json2str(obj: { action: string, data: any }) {
        return JSON.stringify(obj, function (key, val) {
            if (typeof val === "function") {
                val = val.toString();
            }
            return val;
        });
    }

    // 全屏相关
    // 样式对象
    const iframeContainerStyle: React.CSSProperties = {
        position: 'relative',
    };

    const fullScreenBtnStyle: React.CSSProperties = {
        // width: "30px",
        // height: "30px",
        position: "absolute",
        left: "50px",
        bottom: "45px",
        display: "inline-block",
        boxSizing: "border-box", // 修正 box-sizing
        borderRadius: "4px",
        border: "1px solid #999",
        cursor: "pointer",
    };
    const iconStyles = {
        root: {
            color: "#333",
            fontWeight: "bold", // 设置加粗
            fontSize: "24px",   // 设置图标大小
        },
    };
    // 获取url中需要的数据  type  1: 获取文件名  2：获取后缀  3：获取文件名+后缀  4:获取文件前缀
    function urlDemo(url: string, type: number) {
        let filename = url.substring(url.lastIndexOf('/') + 1)
        switch (type) {
            case 1: return filename;
            case 2: return filename.substring(filename.lastIndexOf(".") + 1);
            case 3: return filename.substring(0, filename.lastIndexOf("."));
            case 4: return url.substring(0, url.lastIndexOf('/') + 1)
        }
    }
    // 触发全屏的函数
    const requestFullScreen = () => {
        if (aliyunPreview.current) {
            const iframe = aliyunPreview.current;
            if (iframe.requestFullscreen) {
                iframe.requestFullscreen();
            }
        }
    };

    return (
        <div style={iframeContainerStyle}>
            {isPdf && (
                <div style={fullScreenBtnStyle}>
                    <IconButton
                        iconProps={{ iconName: 'FullScreen', styles: iconStyles }} // 应用样式
                        title="全屏"
                        ariaLabel="全屏"
                        onClick={requestFullScreen} // 点击时触发全屏函数
                    />
                </div>
            )}
            <iframe
                id="aliyunPreview"
                ref={aliyunPreview}
                src="https://preview.imm.aliyun.com/index.html"
                allowFullScreen={true}
                allow="fullscreen"
                frameBorder="0"
                scrolling="no"
                style={{ width: '100%', minHeight: '600px' }}
            />
        </div>
    )
}

export default Sectionw